package nina.yiyou.salary.output

import nina.yiyou.salary.input.util.ExcelReadOpener
import nina.yiyou.salary.input.util.InputPathResolver
import nina.yiyou.salary.output.util.CsvLineMaker
import nina.yiyou.salary.output.util.KeyCellReader
import nina.yiyou.salary.output.util.KeySheetReader
import nina.yiyou.salary.output.util.OutCsvWriter
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.xssf.usermodel.XSSFRow
import org.apache.poi.xssf.usermodel.XSSFSheet

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardCopyOption

class SalaryResultGenerator {

  SalaryResultGenerator(Path workshopPath, List<Map> employeeResult, Map<String, ?> globalResult) {
    _workshopPath = workshopPath
    _employeeResult = employeeResult
    _globalResult = globalResult
  }

  void generate() {
    Path templatePath = _workshopPath.resolveSibling('internal/salary_template.xlsx')
    def (employeeKeys, List globalKeys) = loadTemplateKeys(templatePath)

    Path outPath = new InputPathResolver(_workshopPath, _globalResult['全局.out.工资'] as String).resolve()
    Path tmpDir = Paths.get(outPath.toString() + '_tmp')
    Files.createDirectories(tmpDir)

//    println(tmpDir)
    new EmployeeCsvExporter(_employeeResult, employeeKeys, _globalResult, tmpDir.resolve('employee.csv')).export()
    exportGlobalCsv(globalKeys, tmpDir.resolve('global.csv'))

    Files.copy(templatePath, tmpDir.resolve('template.xlsx'), StandardCopyOption.REPLACE_EXISTING)
  }

  private List loadTemplateKeys(Path templatePath) {
    def workbook = new ExcelReadOpener(templatePath).openXlsx()

    Sheet employeeSheet = workbook.getSheet('员工')
    List<String> employeeKeys = readRowKeys(employeeSheet.getRow(0))

    Sheet globalSheet = workbook.getSheet('全局')
    List<String> globalKeys = new KeySheetReader(globalSheet).readKeys()

    workbook.close()
    return [employeeKeys, globalKeys]
  }

  private List<String> readRowKeys(XSSFRow row) {
    return (0..<row.lastCellNum)
        .collect { row.getCell(it) }
        .collect { new KeyCellReader(it).read() }
  }

  private void exportGlobalCsv(List<String> keys, Path csvPath) {
    new OutCsvWriter(csvPath, keys
        .collect { _globalResult[it] }
        .collect { new CsvLineMaker([it]).make() }).write()
  }

  private final Path _workshopPath

  private final List<Map> _employeeResult
  private final Map<String, ?> _globalResult
}
